<template>
  <div class="post-management-container">
    <h2>帖子管理</h2>
    
    <!-- 筛选区域 -->
    <div class="filter-area">
      <el-select 
        v-model="filterCategory" 
        placeholder="选择疾病分类"
        clearable
        style="width: 200px; margin-right: 10px"
      >
        <el-option label="全部" value="all"></el-option>
        <el-option-group
          v-for="group in diseaseCategories"
          :key="group.label"
          :label="group.label"
        >
          <el-option
            v-for="item in group.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-option-group>
      </el-select>
      
      <el-select 
        v-model="postType" 
        placeholder="选择帖子类型"
        clearable
        style="width: 150px; margin-right: 10px"
      >
        <el-option label="全部" value="all"></el-option>
        <el-option label="经验分享" value="experience"></el-option>
        <el-option label="情感交流" value="emotion"></el-option>
        <el-option label="病情求助" value="help"></el-option>
      </el-select>

      <!-- 新增排序筛选 -->
      <el-select 
        v-model="sortBy" 
        placeholder="选择排序方式"
        clearable
        style="width: 150px; margin-right: 10px"
      >
        <el-option label="发布时间" value="createTime"></el-option>
        <el-option label="获赞数" value="likes"></el-option>
        <el-option label="评论数" value="comments"></el-option>
      </el-select>
      
      <el-input
        v-model="searchQuery"
        placeholder="搜索帖子标题或内容"
        style="width: 300px; margin-right: 10px"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      <!-- 添加导出按钮 -->
      <el-button type="primary" @click="exportToExcel">导出Excel</el-button>
    </div>
    
    <!-- 帖子列表表格 -->
    <el-table 
      :data="filteredPosts" 
      border 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="标题" width="200"></el-table-column>
      <el-table-column prop="author" label="作者" width="120"></el-table-column>
      <el-table-column prop="category" label="分类" width="150"></el-table-column>
      <el-table-column prop="disease" label="疾病" width="150"></el-table-column>
      <el-table-column prop="type" label="帖子类型" width="120">
        <template slot-scope="scope">
          {{ getPostTypeLabel(scope.row.type) }}
        </template>
      </el-table-column>
      <!-- 新增发布时间列 -->
      <el-table-column prop="createTime" label="发布时间" width="180"></el-table-column>
      <el-table-column label="数据" width="180">
        <template slot-scope="scope">
          <div class="post-stats">
            <span>浏览: {{ scope.row.views }}</span>
            <span>点赞: {{ scope.row.likes }}</span>
            <span>收藏: {{ scope.row.favorites }}</span>
            <span>评论: {{ scope.row.comments }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="primary" 
            @click="handleView(scope.row)"
          >
            详情
          </el-button>
          <el-button 
            size="mini" 
            :type="scope.row.isTop ? 'success' : ''"
            @click="toggleTop(scope.row)"
          >
            {{ scope.row.isTop ? '取消置顶' : '置顶' }}
          </el-button>
          <el-button 
            size="mini" 
            :type="scope.row.isFeatured ? 'success' : ''"
            @click="toggleFeatured(scope.row)"
          >
            {{ scope.row.isFeatured ? '取消加精' : '加精' }}
          </el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalPosts"
    ></el-pagination>
    
    <!-- 帖子详情对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="70%"
    >
      <div class="post-detail">
        <h3>{{ currentPost.title }}</h3>
        <div class="post-meta">
          <span>作者: {{ currentPost.author }}</span>
          <span>分类: {{ currentPost.category }}</span>
          <span>疾病: {{ currentPost.disease }}</span>
          <span>发布时间: {{ currentPost.createTime }}</span>
          <span>类型: {{ getPostTypeLabel(currentPost.type) }}</span>
        </div>
        <div class="post-content" v-html="currentPost.content"></div>
        <div class="post-stats">
          <el-tag>浏览: {{ currentPost.views }}</el-tag>
          <el-tag type="success">点赞: {{ currentPost.likes }}</el-tag>
          <el-tag type="warning">收藏: {{ currentPost.favorites }}</el-tag>
          <el-tag type="info">评论: {{ currentPost.comments }}</el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入导出方法
import { exportJsonToExcel } from '@/utils/export2Excel.js';

export default {
  name: 'PostManagement',
  data() {
    return {
      loading: false,
      posts: [],
      searchQuery: '',
      filterCategory: 'all',
      currentPage: 1,
      pageSize: 10,
      totalPosts: 0,
      dialogVisible: false,
      currentPost: {},
      diseaseCategories: [
        {
          label: '罕见病',
          options: [
            { label: '白化病', value: 'albinism' },
            { label: '成骨不全症', value: 'osteogenesis-imperfecta' },
            { label: '戈谢病', value: 'gaucher-disease' },
            { label: '渐冻症', value: 'als' },
            { label: '马凡综合征', value: 'marfan-syndrome' },
            { label: '法布雷病', value: 'fabry-disease' },
            { label: '黏多糖贮积症', value: 'mucopolysaccharidosis' },
            { label: '朗格汉斯细胞组织细胞增多症', value: 'langerhans-cell-histiocytosis' },
            { label: '系统性红斑狼疮', value: 'lupus' },
            { label: '溃疡性结肠炎', value: 'ulcerative-colitis' },
            { label: '消化性溃疡', value: 'peptic-ulcer' },
            { label: '慢性肾病', value: 'chronic-kidney-disease' },
            { label: '传染病', value: 'covid-19' },
            { label: '结核病', value: 'tuberculosis' },
            { label: '疟疾', value: 'malaria' },
            { label: '精神分裂症', value: 'schizophrenia' },
            { label: '强迫症', value: 'ocd' },
          ]
        },
        {
          label: '癌症',
          options: [
            { label: '肺癌', value: 'lung-cancer' },
            { label: '鼻咽癌', value: 'nasopharyngeal-carcinoma' },
            { label: '乳腺癌', value: 'breast-cancer' },
            { label: '宫颈癌', value: 'cervical-cancer' },
            { label: '胃癌', value: 'gastric-cancer' },
            { label: '肝癌', value: 'liver-cancer' },
            { label: '白血病', value: 'leukemia' },
            { label: '淋巴瘤', value: 'lymphoma' },
            { label: '膀胱癌', value: 'bladder-cancer' },
            { label: '前列腺癌', value: 'prostate-cancer' },
            { label: '甲状腺癌', value: 'thyroid-cancer' },
            { label: '脑癌', value: 'brain-cancer' },
          ]
        },
        {
          label: '慢性病',
          options: [
            { label: '高血压', value: 'hypertension' },
            { label: '冠心病', value: 'coronary-heart-disease' },
            { label: '糖尿病', value: 'diabetes' },
            { label: '痛风', value: 'gout' },
            { label: '慢性阻塞性肺疾病', value: 'copd' },
            { label: '骨质疏松症', value: 'osteoporosis' },
            { label: '阿尔茨海默病', value: 'alzheimers' },
            { label: '消化性溃疡', value: 'peptic-ulcer' },
            { label: '慢性肾病', value: 'chronic-kidney-disease' },
          ]
        },
        {
          label: '传染病',
          options: [
            { label: '流感', value: 'influenza' },
            { label: '新冠肺炎', value: 'covid-19' },
            { label: '结核病', value: 'tuberculosis' },
            { label: '疟疾', value: 'malaria' },
          ]
        },
        {
          label: '精神疾病',
          options: [
            { label: '抑郁症', value: 'depression' },
            { label: '焦虑症', value: 'anxiety' },
            { label: '精神分裂症', value: 'schizophrenia' },
            { label: '强迫症', value: 'ocd' },
          ]
        },
        {
          label: '自身免疫性疾病',
          options: [
            { label: '类风湿关节炎', value: 'rheumatoid-arthritis' },
            { label: '系统性红斑狼疮', value: 'lupus' },
            { label: '溃疡性结肠炎', value: 'ulcerative-colitis' },
            { label: '消化系统自身免疫病', value: 'ulcerative-colitis' },
          ]
        }
      ],
      postType: 'all',
      // 新增排序相关数据
      sortBy: ''
    }
  },
  computed: {
    filteredPosts() {
      let filtered = this.posts.filter(post => {
        if (this.filterCategory !== 'all' && post.category !== this.filterCategory) {
          return false
        }
        if (this.postType !== 'all' && post.type !== this.postType) {
          return false
        }
        if (this.searchQuery && 
            !post.title.includes(this.searchQuery) && 
            !post.content.includes(this.searchQuery)) {
          return false
        }
        return true
      });

      // 排序逻辑
      if (this.sortBy) {
        filtered.sort((a, b) => {
          if (this.sortBy === 'createTime') {
            return new Date(b[this.sortBy]) - new Date(a[this.sortBy]);
          }
          return b[this.sortBy] - a[this.sortBy];
        });
      }

      return filtered.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  created() {
    this.fetchPosts()
  },
  methods: {
    fetchPosts() {
      this.loading = true
      // 模拟API调用
      setTimeout(() => {
        this.posts = [
          {
            id: 1,
            title: '关于抑郁症的自我调节方法',
            author: '张三',
            category: '精神疾病',
            disease: '抑郁症',
            views: 1254,
            likes: 256,
            favorites: 98,
            comments: 45,
            isTop: true,
            isFeatured: false,
            createTime: '2023-05-15 14:30:22',
            content: '<p>抑郁症是一种常见的精神疾病...</p>',
            type: 'experience' 
          },
          // 更多模拟数据...
        ]
        this.totalPosts = this.posts.length
        this.loading = false
      }, 500)
    },
    getPostTypeLabel(type) {
      const typeMap = {
        'experience': '经验分享',
        'emotion': '情感交流',
        'help': '病情求助',
        'all': '全部'
      };
      return typeMap[type] || type;
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchPosts()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchPosts()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchPosts()
    },
    handleView(post) {
      this.currentPost = post
      this.dialogVisible = true
    },
    toggleTop(post) {
      post.isTop = !post.isTop
      const action = post.isTop ? '置顶' : '取消置顶'
      this.$message.success(`${action}成功`)
    },
    toggleFeatured(post) {
      post.isFeatured = !post.isFeatured
      const action = post.isFeatured ? '加精' : '取消加精'
      this.$message.success(`${action}成功`)
    },
    handleDelete(post) {
      this.$confirm('确定要删除此帖子吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.posts.findIndex(p => p.id === post.id)
        this.posts.splice(index, 1)
        this.totalPosts--
        this.$message.success('删除成功')
      })
    },
    // 添加导出Excel方法
    exportToExcel() {
      const tHeader = ['ID', '标题', '作者', '分类', '疾病', '帖子类型', '发布时间', '浏览', '点赞', '收藏', '评论'];
      const data = this.posts.map(post => ({
        'ID': post.id,
        '标题': post.title,
        '作者': post.author,
        '分类': post.category,
        '疾病': post.disease,
        '帖子类型': this.getPostTypeLabel(post.type),
        '发布时间': post.createTime,
        '浏览': post.views,
        '点赞': post.likes,
        '收藏': post.favorites,
        '评论': post.comments
      }));
      exportJsonToExcel(tHeader, data, '帖子列表');
    },
  }
}
</script>

<style scoped>
.post-management-container {
  padding: 20px;
}

.filter-area {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-end; /* 让子元素底部对齐 */
}

.radio-group {
  font-size: 16px; /* 增大字体大小，可根据实际情况调整 */
  margin-right: 10px;
}

.post-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.post-stats span {
  margin-right: 10px;
  font-size: 12px;
  color: #666;
}

.post-detail h3 {
  margin-bottom: 15px;
  color: #333;
}

.post-meta {
  margin-bottom: 15px;
  color: #999;
  font-size: 14px;
}

.post-meta span {
  margin-right: 15px;
}

.post-content {
  line-height: 1.6;
  margin-bottom: 20px;
}
</style>